package cn.rocksolid.sport.common.mq;

import cn.rocksolid.sport.common.Constant.MQ;
import org.apache.activemq.ScheduledMessage;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

import java.io.Serializable;

@Component
public final class MqHelper {

  private final JmsTemplate jmsTemplate;

  @Autowired
  public MqHelper(@Qualifier(MQ.JMS_TEMPLATE_NAME) final JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
  }

  public <M extends Serializable> void pub(final String topic, final M msg) {
    jmsTemplate.convertAndSend(new ActiveMQTopic(topic), msg);
  }

  public <M extends Serializable> void pub(final String topic, final M msg, final long delay) {
    jmsTemplate.convertAndSend(new ActiveMQTopic(topic), msg, postMsg -> {
      postMsg.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);
      return postMsg;
    });
  }
}
